package com.cs2.volunteerpostbackend.web.controller;

import com.cs2.volunteerpostbackend.po.Moment;
import com.cs2.volunteerpostbackend.service.MomentService;
import com.cs2.volunteerpostbackend.service.impl.MessageService;
import com.cs2.volunteerpostbackend.web.dto.RespEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/email")
public class EmailController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private MomentService momentService;

    /**
     * 发送邮件请求，邮件内容为指定动态的内容
     * POST /api/email/send/{momentId}
     */
    @PostMapping("/send/{momentId}")
    public RespEntity sendEmailWithMoment(@PathVariable String momentId,
                                          @RequestParam String recipientEmail) {
        System.out.println("=== 接收发送邮件请求 ===");
        System.out.println("动态ID: " + momentId);
        System.out.println("收件人邮箱: " + recipientEmail);

        try {
            // 通过反射获取MomentServiceImpl中的momentMapper来查询动态
            Moment moment = ((com.cs2.volunteerpostbackend.service.impl.MomentServiceImpl) momentService).getBaseMapper().selectById(momentId);

            if (moment == null) {
                System.err.println("未找到指定的动态，ID: " + momentId);
                return new RespEntity("404", "未找到指定的动态", null);
            }

            // 将收件人邮箱信息添加到动态对象中
            // 这里我们使用扩展字段来传递邮箱信息
            moment.setPosterId(recipientEmail); // 临时借用posterId字段存储收件人邮箱

            // 发送动态到邮件队列
            messageService.sendMomentToEmailQueue(moment);

            System.out.println("邮件发送请求已提交，动态标题: " + moment.getTitle());
            return new RespEntity("200", "邮件发送请求已提交", moment);
        } catch (Exception e) {
            System.err.println("发送邮件失败: " + e.getMessage());
            return new RespEntity("500", "发送邮件失败: " + e.getMessage(), null);
        }
    }
}